<template>
  <scroll-view class="detail-container" scroll-y="true" @scrolltolower="onScrollToLower" refresher-enabled="true" :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
    <!-- 头部：标题 + 状态 -->
    <view class="detail-header">
      <view class="order-title">工单详情</view>
      <view class="order-status" :style="{ backgroundColor: statusColor, color: '#fff' }">
        {{ statusText }}
      </view>
    </view>

    <!-- 详情卡片：静态数据展示 -->
    <view class="detail-card">
      <view class="detail-item">
        <view class="label">工单编号</view>
        <view class="value">{{ order.id }}</view>
      </view>
      <view class="detail-item">
        <view class="label">工单标题</view>
        <view class="value">{{ order.title }}</view>
      </view>
      <view class="detail-item">
        <view class="label">工单描述</view>
        <view class="value">{{ order.des || '无描述' }}</view>
      </view>
      <view class="detail-item">
        <view class="label">联系人姓名</view>
        <view class="value">{{ order.name }}</view>
      </view>
      <view class="detail-item">
        <view class="label">联系人电话</view>
        <view class="value">{{ order.phone }}</view>
      </view>
      <view class="detail-item">
        <view class="label">服务地址</view>
        <view class="value">{{ order.address }}</view>
      </view>
      <view class="detail-item">
        <view class="label">支付状态</view>
        <view class="value">{{ order.payStatus }}</view>
      </view>
      <view class="detail-item">
        <view class="label">工单状态</view>
        <view class="value">{{ statusText }}</view>
      </view>
      <view class="detail-item">
        <view class="label">工单类型</view>
        <view class="value">{{ getOrderTypeText(order.type) }}</view>
      </view>
      <view class="detail-item">
        <view class="label">工单更新时间 </view>
        <view class="value">:{{  order.updateTime }}</view>
      </view>
      <view class="detail-item">
        <view class="label">服务报酬</view>
        <view class="value" style="color: #dd524d;">¥{{ order.price }}</view>
      </view>
      <view class="detail-item">
        <view class="label">分配师傅</view>
        <view class="value">{{ order.masterName || '暂无' }}</view>
      </view>
      <view class="detail-item">
        <view class="label">工单创建时间</view>
        <view class="value">:{{order.createTime }}</view>
      </view>
    </view>

    <!-- 服务报酬输入区域 -->
    <view class="detail-card" v-if="order.status === 1">
      <view class="detail-item">
        <view class="label">基础费用</view>
        <input 
          class="price-input" 
          type="digit" 
          v-model="pay" 
          placeholder="请输入基础费用" 
        />
      </view>
      <view class="detail-item">
        <view class="label">服务报酬</view>
        <input 
          class="price-input" 
          type="digit" 
          v-model="servicePay" 
          placeholder="请输入服务报酬" 
        />
      </view>
    </view>

    <!-- 操作按钮：仅待处理状态显示 -->
    <view class="action-btns" v-if="order.status !== 2">
      <button class="complete-btn" @click="completeOrderHandler">标记完成</button>
      <button class="cancel-btn" @click="cancelOrder">取消工单</button>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, onMounted, onActivated } from 'vue';
import { getOrderList, completeOrder } from '../../api/order.js'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 工单数据
const order = ref({
  id: '',
  title: '',
  description: '',
  demand: '',
  customerName: '',
  customerPhone: '',
  address: '',
  payStatus: 0, // 0: 未支付, 1: 已支付
  status: 1, // 1: 待处理, 2: 已完成, 3: 已取消
  type: 0, // 0: 普通, 1: 紧急
  time: '',
  price: 0,
  masterName: '',
  createTime: ''
});

// 服务报酬
const servicePay = ref('');
// 基础费用
const pay = ref('');

// 状态文本和颜色
const statusText = ref('');
const statusColor = ref('');
const payStatusText = ref('');

// 下拉刷新状态
const refreshing = ref(false);

let currentOrderId = null;

// 页面加载时获取工单详情
onLoad(async (options) => {
  if (options && options.id) {
    currentOrderId = options.id;
    await fetchOrderDetail(options.id);
  }
});

// 页面显示时刷新工单详情，但不检查登录状态
onShow(async () => {
  // 如果有当前工单ID，则刷新数据
  if (currentOrderId) {
    await fetchOrderDetail(currentOrderId);
  }
});

// 页面被激活时也刷新数据
onActivated(async () => {
  // 如果有当前工单ID，则刷新数据
  if (currentOrderId) {
    await fetchOrderDetail(currentOrderId);
  }
});

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  if (currentOrderId) {
    await fetchOrderDetail(currentOrderId);
  }
  refreshing.value = false;
};

// 获取工单详情
const fetchOrderDetail = async (orderId) => {
  try {
    const res = await getOrderList();
    if (res && res.code === 0) {
      // 从列表中找到匹配的工单
      const orderDetail = (res.data || []).find(item => item.id == orderId);
      if (orderDetail) {
        order.value = orderDetail;
        updateStatusInfo();
        updatePayStatusInfo();
      } else {
        uni.showToast({
          title: '未找到该工单',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: res?.msg || '获取工单详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取工单详情失败:', error);
    uni.showToast({
      title: '获取工单详情失败',
      icon: 'none'
    });
  }
};

// 获取工单类型文本
const getOrderTypeText = (type) => {
  const map = {
    0: '普通',
    1: '紧急'
  };
  return map[type] || '未知类型';
};

// 更新状态文本和颜色
const updateStatusInfo = () => {
  switch (order.value.status) {
    case 1:
      statusText.value = '待处理';
      statusColor.value = '#f0ad4e'; // 黄色
      break;
    case 2:
      statusText.value = '已完成';
      statusColor.value = '#4cd964'; // 绿色
      break;
    case 3:
      statusText.value = '已取消';
      statusColor.value = '#999'; // 灰色
      break;
    default:
      statusText.value = '未知状态';
      statusColor.value = '#666';
  }
};

// 更新支付状态文本
const updatePayStatusInfo = () => {
  switch (order.value.payStatus) {
    case 0:
      payStatusText.value = '未支付';
      break;
    case 1:
      payStatusText.value = '已支付';
      break;
    default:
      payStatusText.value = '未知';
  }
};

// 标记完成
const completeOrderHandler = async () => {
  // 验证基础费用是否已输入
  if (!pay.value || isNaN(pay.value) || parseFloat(pay.value) <= 0) {
    uni.showToast({
      title: '请输入有效的基础费用',
      icon: 'none'
    });
    return;
  }
  
  // 验证服务报酬是否已输入
  if (!servicePay.value || isNaN(servicePay.value) || parseFloat(servicePay.value) <= 0) {
    uni.showToast({
      title: '请输入有效的服务报酬',
      icon: 'none'
    });
    return;
  }

  uni.showModal({
    title: '确认完成',
    content: '确认已完成服务吗？',
    confirmText: '确认',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '处理中...' });
          
          // 准备数据
          const completeData = {
            orderId: order.value.id,
            pay: parseFloat(pay.value),
            servicePay: parseFloat(servicePay.value)
          };

          // 如果有产品ID，添加到请求数据中
          if (order.value.productId) {
            completeData.productId = order.value.productId;
          }

          // 调用新的完成订单接口（需要后端实现）
          // 这里应该传递完整数据对象
          const response = await completeOrder(completeData);
          
          if (response && response.code === 0) {
            // 更新本地状态
            order.value.status = 2;
            updateStatusInfo();
            uni.showToast({
              title: '工单已完成',
              icon: 'success',
              duration: 1500
            });
          } else {
            uni.showToast({
              title: response?.msg || '完成工单失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('完成工单失败:', error);
          uni.showToast({
            title: '完成工单失败',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

// 取消工单
const cancelOrder = () => {
  uni.showModal({
    title: '确认取消',
    content: '取消后此工单将无法恢复，是否继续？',
    confirmText: '继续取消',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        // 这里应该调用后端接口取消工单
        uni.showToast({
          title: '工单已取消',
          icon: 'none',
          duration: 1500
        });
      }
    }
  });
};
</script>

<style scoped>
/* 页面容器：全屏背景 + 内边距 */
.detail-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 头部：标题 + 状态 */
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}
.order-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}
.order-status {
  padding: 8rpx 18rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

/* 详情卡片：白色背景 + 阴影 + 内边距 */
.detail-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 32rpx;
}
/* 详情项：标签 + 内容 横向布局 */
.detail-item {
  display: flex;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  align-items: flex-start; /* 适应长文本换行 */
}
/* 最后一项移除下边框 */
.detail-item:last-child {
  border-bottom: none;
}
.label {
  width: 160rpx;
  font-size: 26rpx;
  color: #666;
  padding-top: 2rpx; /* 对齐文本基线 */
}
.value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  word-break: break-all; /* 长地址/需求自动换行 */
  line-height: 40rpx; /* 行高优化，提升可读性 */
}

/* 服务报酬输入框 */
.price-input {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  padding: 10rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  text-align: right;
}

/* 操作按钮：双按钮横向布局 */
.action-btns {
  display: flex;
  gap: 20rpx;
  padding: 0 20rpx 20rpx; /* 底部内边距，避免按钮贴底 */
  box-sizing: border-box;
  margin-top: 20rpx;
}
.complete-btn {
  flex: 1;
  height: 88rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 44rpx;
  font-size: 28rpx;
}
.cancel-btn {
  flex: 1;
  height: 88rpx;
  background-color: #fff;
  color: #666;
  border: 1rpx solid #eee;
  border-radius: 44rpx;
  font-size: 28rpx;
}
</style>